// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: process.env.Env })
const dateUtils = require('date-utils')
const db = cloud.database()
const _ = db.command

//收到评论通知
const template = '_Denf6vPB21lJlS_BsDabG65_DLarNxdD1VyuRJD94M'
// const template = '_Denf6vPB21lJlS_BsDabH03Xz0VgIUcD-O9RrH7H48'

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  switch (event.action) {
    case 'sendTemplateMessage': {
      return sendTemplateMessage(event)
    }
    default: break
  }
}


/**
 * 发送通知消息
 * @param  event 
 */
async function sendTemplateMessage(event) {

  if (event.userInfo.openId == event.toOpenId) {
    console.log('same user return')
    return
  }

  var toOpenId = [];

  if (event.toOpenId !== undefined && event.toOpenId != '') {
    toOpenId.push(event.toOpenId)
  }
  console.info('send msg -> ', toOpenId, ' time -> ', new Date(Date.now() + (8 * 60 * 60 * 1000)).toFormat("YYYY-MM-DD HH24:MI:SS"))
  //
  let res = await db.collection('mini_form_ids').field({
    _id: true
  }).limit(5).get()
  if (res.data.length == 0) {
    return
  }

  var formIds = res.data
  console.info('send msg -> ', toOpenId, ' formIds -> ', formIds)
  if (toOpenId.length == 0 || formIds.length == 0) {
    return
  }
  var sendResult = {}
  for (var formId of formIds) {
    try {
      sendResult = await cloud.openapi.templateMessage.send({
        touser: toOpenId[0],
        templateId: template,
        formId: formId._id,
        page: 'pages/detail/detail?id=' + event.blogId,
        data: {
          keyword1: {
            value: event.nickName
          },
          keyword2: {
            value: event.message
          },
          keyword3: {
            value: new Date(Date.now() + (8 * 60 * 60 * 1000)).toFormat("YYYY-MM-DD HH24:MI:SS")
          },
          keyword4: {
            value: event.remark
          }
        },
      })
      console.info('send msg -> ', toOpenId, ' formId -> ', formId._id)
      break
    } catch(e) {
      console.error('formId ->', formId._id, ' errorCode -> ', e.errCode,' error -> ', e.errMsg)
    } finally {
      await db.collection('mini_form_ids').doc(formId._id).remove()
    }
  }


  return sendResult
}
/**
 * 获取总的formIds和过期的formIds
 * @param {} event 
 */
async function queryFormIds(event) {
  var data = {}
  var formIdsResult = await db.collection('mini_formids').where({
    openId: process.env.author // 填入当前用户 openid
  }).count()

  /*var formIdsExpireResult = await db.collection('mini_formids').where({
    openId: process.env.author, // 填入当前用户 openid
    timestamp: _.lt(new Date().removeDays(7).getTime())
  }).count()*/

  data.formIds = formIdsResult.total
  //data.expireFromIds = formIdsExpireResult.total
  return data;
}

/**
 * 删除过期的formID
 * @param {} event 
 */
async function removeExpireFormId(event) {
  try {
    return await db.collection('mini_formids').where({
      timestamp: _.lt(new Date().removeDays(7).getTime())
    }).remove()
  } catch (e) {
    console.error(e)
  }
}

/**
 * 新增formId
 * @param {} event 
 */
async function addFormIds(event) {
  try {

    let removeRes = await db.collection('mini_formids').where({
      timestamp: _.lt(new Date().removeDays(7).getTime())
    }).remove()

    console.info(removeRes)

    for (var i = 0; i < event.formIds.length; i++) {
      let data = {
        openId: event.userInfo.openId,
        formId: event.formIds[i],
        timestamp: new Date().getTime()
      }

      let res = await db.collection('mini_formids').add({
        data: data
      })
      console.info(res)
    }
    return true;
  } catch (e) {
    console.error(e)
    return false;
  }
}
